package com.howie.parnote.util;

import java.util.Random;

import org.apache.commons.lang3.StringUtils;


public class RandomStringUtil {

	public static String randomString(int length) {

		String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random = new Random();
		StringBuffer buf = new StringBuffer();

		for (int i = 0; i < length; i++) {
			int num = random.nextInt(62);
			buf.append(str.charAt(num));
		}

		return buf.toString();
	}

	public static String getRandomCode() {
		return System.currentTimeMillis() + randomString(12);
	}

	public static Object[] getRandomSequence(String code) {
		Random rd = new Random();
		StringBuffer sequence = new StringBuffer();
		StringBuffer sequenceCode = new StringBuffer();
		for (int i = 0; i < 6; i++) {
			Integer num = rd.nextInt(code.length());
			sequenceCode.append(code.charAt(num));
			if (i == 0 || i == 6)
				sequence.append(num);
			else
				sequence.append("_" + num);

		}
		return new Object[] { sequenceCode, sequence };
	}

	public static boolean sequenceDecode(String sequenceCode, String sequence, String originalCode) {
		boolean result = false;
		StringBuffer matchCode = new StringBuffer();
		String[] sequences = sequence.split("_");
		for (String num : sequences) {
			matchCode.append(originalCode.charAt(Integer.valueOf(num)));
		}
		if (StringUtils.equals(matchCode.toString(), sequenceCode)) {
			result = true;
		}
		return result;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		System.out.println(getRandomSequence("TO1386134677631FeSb70TwkVR3"));
	}

}
